import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // vue的插件机制


import {
	companyInfo,getUserInfo
} from '@/common/api.js'
// Vuex.Store 构造器选项
const store = new Vuex.Store({
	// 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
	state: {
		// 用户信息
		$userInfo: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo') : {},
		token: uni.getStorageSync('token') ? uni.getStorageSync('token') : null,
		isLogin: uni.getStorageSync('token') ? true : false,
		// 分站信息
		$companyInfo: uni.getStorageSync('companyInfo') ? uni.getStorageSync('companyInfo') : {},
	},
	mutations: {
		setUserInfo: (state, data) => {
			uni.setStorageSync('userInfo', data);
			uni.setStorageSync('token', data.token);

			state.$userInfo = uni.getStorageSync('userInfo');
			state.token = uni.getStorageSync('token');
			state.isLogin = true;
		},
		setInitData(state, data) {
			state.siteData = data.site
		},
		setUserLogout: (state, data) => {
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('token');
		
			state.isLogin = false;
		},
	},
	actions: {
		setUserLogout(context) {
			context.commit('setUserLogout')
		},
		getUserInfo(context) {
			getUserInfo().then(res => {
				console.log('userinfo', res)
				context.commit('setUserInfo', res.userinfo)
			}).catch(err => {
				return Promise.reject(err)
			})
		},
		getInitData({
			state,
			commit
		}) {
			init().then(res => {
				// context.commit('setInitData', res)
				state.siteData = res.site
			}).catch(err => {
				return Promise.reject(err)
			})
		},
		getCompanyInfo({
			state,
			commit
		}) {
			companyInfo().then(res => {
				// context.commit('setInitData', res)
				uni.setStorageSync('companyInfo', res.info);
				state.$companyInfo = uni.getStorageSync('companyInfo');
			}).catch(err => {
				return Promise.reject(err)
			})
		}
	}
})

export default store